<template>
  <nav-bar>
      <template v-slot:default>新用户注册</template>
  </nav-bar>    
  <img src="~img/whpu.png" class="logo">    
  <div class="container">
    <!--form表单容器-->
    <div class="forms-container">

        <!--登录-->
        <el-form :model="registerUser" ref="lbRegister" label-width="80px"  :rules="rules" class="loginForm">
          <el-form-item label="用户名" prop="name">
            <el-input v-model="registerUser.name" placeholder="请输入用户名..."></el-input>
          </el-form-item>
          <el-form-item label="密&nbsp;&nbsp;&nbsp;码" prop="password">
            <el-input v-model="registerUser.password" type="password" placeholder="请输入密码..."></el-input>
          </el-form-item>
           <el-form-item label="确认密码" prop="password2">
            <el-input v-model="registerUser.password2" type="password" placeholder="请输入密码..."></el-input>
          </el-form-item>
          <el-form-item label="选择角色" prop="role">
            <el-select v-model="registerUser.role"  placeholder="请选择角色...">
              <el-option label="管理员" value="admin"></el-option>
              <el-option label="用户" value="user"></el-option>
              <el-option label="游客" value="visitor"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="success" class="submit-btn" @click="onSubmit('lbRegister')">注册</el-button>
          </el-form-item>
        </el-form>
         <div class="tiparea">
	<p>已有密码，<a href="/login">登录</a></p>
        </div>
      </div>
  </div>
  <el-button type="success" @click="test"></el-button>
</template>

<script>
import { reactive, toRefs, getCurrentInstance } from 'vue'
import { useRouter } from 'vue-router'
import NavBar from '../../components/common/navbar/NavBar.vue'
import axios from 'axios'
export default {
  name: 'LoginRegister',
  components:{
    NavBar
  },
  setup () {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== state.registerUser.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
     const checkName= (rule, value, callback) => {
      //let userName=['hello','abc','admin'] // 假设这些用户已在服务器注册
      //let flag=userName.includes(value) // 以后可以使用axios去服务器查询
      axios.get('/api/register.php',{
        params: {
          username: value
        }
      }).then(res =>{
        if (res.data) {         // 返回true或者false
          callback(new Error('用户名已存在，请重新输入用户名'))
        } else {
          callback()
        }

      }).catch(
          error => {
            window.console.log("失败"+error)
      })
      
    }
    const state = reactive({
      registerUser: {
        name: '',
        password: '',
        password2: '',
        role: ''
      },
      flag: 'true',
      rules: { // 校验规则
        name: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          },
          {
            min: 2,
            max: 25,
            message: '用户名长度必须在 2 到 25 个字符',
            trigger: 'blur'
          },
          {
            validator: checkName,
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          },
          {
            min: 6,
            max: 15,
            message: '密码长度必须在 6 到 15 个字符',
            trigger: 'blur'
          }
        ],
        password2: [
          {
            required: true,
            message: '请输入确认密码',
            trigger: 'blur'
          },
          {
            min: 6,
            max: 15,
            message: '确认密码长度必须在 6 到 15 个字符',
            trigger: 'blur'
          },
          {
            validator: validatePass,
            trigger: 'blur'
          }
        ],
        role: [
          {
            required: true,
            message: '请选择角色',
            trigger: 'blur'
          }
        ]
      }
    })
    const { ctx } = getCurrentInstance()
    const router = useRouter()
    // 触发方法
    const onSubmit = (formName) => {
      ctx.$refs[formName].validate((valid) => {
        if (valid) {
          
          axios.get('/api/register.php',{
            params: {
              username: state.registerUser.name,
              password: state.registerUser.password,
              role: state.registerUser.role
              }
          }).then(res =>{
              if (res.data) {         // 返回true或者false
                
                router.push('/login')
              }
            }).catch(
              error => {
                window.console.log("失败"+error)
              })
          
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
    const test = () => {
        ctx.$confirm('确定注册, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
          ctx.$message({
            type: 'success',
            message: '注册成功!'
          });
        }).catch(() => {
          ctx.$message({
            type: 'info',
            message: '已取消注册'
          });
        });
      }
    return {
      ...toRefs(state),
      onSubmit,
      test
    }
  }
}
</script>

<style scoped>
.logo{
    width: 70%;
    margin-top:75px;
}
.container{
  position: relative;
  width: 100%;
  background-color: #fff;
  min-height: 300px;
  overflow: hidden;
}
.forms-container{
  width:100%;
  margin:20px auto;
  padding: 20px;
  /* border-radius: 6px;
  border:1px solid #dcdfe6;
  box-shadow: 5px 5px 30px #dcdfe6; */
}
.login-title{
  text-align: center;
  font-weight: bolder;
  margin-bottom: 30px;
}
.submit-btn{
  width: 100%;
}
.tiparea{
  text-align: right;
  font-size: 12px;
  color: #333;
}
.tiparea p a{
  color: #409eff;
  text-decoration: none;
}
</style>